package com.jayanslow.lighting.protocol.commands;

import com.jayanslow.lighting.protocol.misc.Bytes;
import com.jayanslow.lighting.protocol.misc.CharacterEncoding;


public class Net {
	public static final short MAX_NAME_LENGTH = 16;
	public enum NetDevice {
		STANDARD (0x01), MOBILE (0x02), BACKUP (0x03);
		private NetDevice(int s) { this.code = (short) s; }
		private final short code;
		public short getCode() { return code; }
		public static NetDevice valueOf(short s) { 
			for (NetDevice t : NetDevice.values()) { if (t.getCode() == s) return t; }
			return null;
		}
	}
	
	public enum NetCommand {
		CONNECT (0xD0), CONNECT_NAME (0xD1), DISCONNECT (0xD2), NAME (0xD3), REGISTER (0xD4), UNREGISTER (0xD5);
		private NetCommand(int s) { this.code = (short) s; }
		private final short code;
		public short getCode() { return code; }
		public static NetCommand valueOf(short s) { 
			for (NetCommand c : NetCommand.values()) { if (c.getCode() == s) return c; }
			return null;
		}
	}
	
	public static short[] connect(NetDevice type) {
		short code = NetCommand.CONNECT.getCode();

		if (type == null) type = NetDevice.STANDARD;
		
		return new short[] { code, type.getCode() };
	}
	public static short[] connect(NetDevice type, String name) {
		short code = NetCommand.CONNECT_NAME.getCode();

		if (type == null) type = NetDevice.STANDARD;

		name = CharacterEncoding.CHAR64.clean(name);
		if (name.length() > MAX_NAME_LENGTH) name = name.substring(0, MAX_NAME_LENGTH);
		short[] nameSS = Bytes.toBytes(CharacterEncoding.CHAR64.decode(name),12);
		
		short[] r = new short[14];
		r[0] = code;
		r[1] = type.getCode();
		for (int i = 0; i < 12; i++) {
			r[2 + i] = nameSS[i];
		}
		
		return r;
	}
	public static short[] disconnect() {
		short code = NetCommand.DISCONNECT.getCode();
		return new short[] { code };
	}
	public static short[] changeName(String name) {
		short code = NetCommand.NAME.getCode();

		name = CharacterEncoding.CHAR64.clean(name);
		if (name.length() > MAX_NAME_LENGTH) name = name.substring(0, MAX_NAME_LENGTH);
		short[] nameSS = Bytes.toBytes(CharacterEncoding.CHAR64.decode(name),12);

		short[] r = new short[13];
		r[0] = code;
		for (int i = 0; i < 12; i++) {
			r[1 + i] = nameSS[i];
		}
		
		return r;
	}
	public static short[] register() {
		short code = NetCommand.REGISTER.getCode();
		return new short[] { code };
	}
	public static short[] unregister() {
		short code = NetCommand.UNREGISTER.getCode();
		return new short[] { code };
	}
	
}
